package com.bdqn.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.bdqn.pojo.Role;
import com.bdqn.pojo.User;
import com.bdqn.service.RoleService;
import com.bdqn.service.UserService;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/user")
public class UserController {
    @Resource
    UserService userService;
    @Resource
    RoleService roleService;

    @RequestMapping("/list")
    public String list(Model model, String usrName, Long roleId, Long pageIndex) {
        model.addAttribute("usrName", usrName);
        model.addAttribute("roleId", roleId);
        // 获取所有权限数据填充下拉框
        List<Role> allRoles = roleService.findAllRoles();
        model.addAttribute("roles", allRoles);
        if (pageIndex == null) {
            pageIndex = 0L;
        }
        // 使用页面传递的参数分页查询用户列表
        Page<User> page = new Page<>();
        page.setCurrent(pageIndex);
        page.setSize(5);
        IPage<User> userPager = userService.findUsers(usrName, roleId, page);
        for (User record : userPager.getRecords()) {
            System.out.println(record.toString());
        }
        model.addAttribute("userPager", userPager);

        return "user/list";
    }

    @RequestMapping("/add")
    public String add(Model model) {
        List<Role> allRoles = roleService.findAllRoles();
        model.addAttribute("roles", allRoles);
        return "user/add";
    }

    @RequestMapping("/save")
    public String save(User user) {
        userService.saveUser(user);
        return "redirect:/user/list";

    }

    @RequestMapping("/edit")
    public String edit(Long usrId, Model model) {
        System.out.println("*/*/*/*/*/*/*/*/*/*/*/0" + usrId);
        List<Role> allRoles = roleService.findAllRoles();
        model.addAttribute("roles", allRoles);
        User user = userService.getUser(usrId);
        model.addAttribute("user", user);
        return "user/edit";
    }

    @RequestMapping("/del/{usrId}")
    @ResponseBody
    public String del(@PathVariable("usrId") Long usrId) {
        System.out.println("****/////*"+usrId);
        boolean aa=userService.deleteUser(usrId);


        return "{\"delResult\":\"" + aa + "\"}";
    }


}
